/**
 * @Title: hyInformationVerifyController.java
 * @Package com.hanyong.admin.controller.hyInformationVerify
 * @Description: TODO(用一句话描述该文件做什么)
 * @author Li
 * @date 2018年9月26日 上午9:19:38
 * @version V1.0
 */
package com.hyfrogx.modules.information.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyfrogx.common.qcloud.UploadUtils;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.form.information.VerifyMediaForm;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.app.utils.StringUtils;
import com.hyfrogx.modules.information.entity.HyInformationOrderEntity;
import com.hyfrogx.modules.information.entity.HyInformationVerifyEntity;
import com.hyfrogx.modules.information.entity.HyVerifyPriceEntity;
import com.hyfrogx.modules.information.form.EditCompanyProfileForm;
import com.hyfrogx.modules.information.form.EditVerifyForm;
import com.hyfrogx.modules.information.form.EnableMediaForm;
import com.hyfrogx.modules.information.form.RecommendForm;
import com.hyfrogx.modules.information.service.HyInformationOrderService;
import com.hyfrogx.modules.information.service.HyInformationVerifyService;
import com.hyfrogx.modules.information.service.HyVerifyPriceService;
import com.hyfrogx.modules.sys.controller.AbstractController;
import com.hyfrogx.modules.sys.entity.SysUserEntity;
import com.hyfrogx.modules.sys.entity.SysUserRoleEntity;
import com.hyfrogx.modules.sys.service.SysUserRoleService;
import com.hyfrogx.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author Li
 * @ClassName: hyInformationVerifyController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date 2018年9月26日 上午9:19:38
 */

@RestController
@RequestMapping(value = "informationVerify")
@Api(value = "HyInformationVerifyController", tags = {"后台--资讯号审核管理"})
public class HyInformationVerifyController extends AbstractController {
  @Autowired
  private HyInformationVerifyService hyInformationVerifyService;
  @Autowired
  private HyInformationOrderService orderService;
  @Autowired
  private SysUserService sysUserService;
  @Autowired
  private SysUserRoleService sysUserRoleService;
  @Autowired
  private UserService userService;


  @RequestMapping(value = "verificationInformation", method = RequestMethod.POST)
  @ApiOperation("后台编辑审核")
  public R verify(@RequestBody EditVerifyForm hyInformationVerify) {
    SysUserEntity user = getUser();
    if (ObjectUtil.isNotNull(user)) {
      HyInformationVerifyEntity result = hyInformationVerifyService.getVerifyRecordByUid(hyInformationVerify.getUid());
      BeanUtils.copyProperties(hyInformationVerify, result);
      result.setAuthenticationTime(new Date());
      result.setAuditorUid(getUserId().intValue());
      result.setAuditorname(user.getUsername());
      result.setAuditorPhone(user.getMobile());

      if (hyInformationVerify.getVerifyStatus() == FrogConstant.InformationVerify.PASS) {
        // 查询订单
        HyInformationOrderEntity order = orderService.getBaseMapper()
          .selectOne(new QueryWrapper<HyInformationOrderEntity>().eq("uid", hyInformationVerify.getUid()));
        // 因为存在后台创建的认证信息,无法从admin扣除蛙豆生成订单,
        // 所以审核通过时,需要判断订单存不存在,走客户端提交的认证,在初次提交一定支付蛙豆存在订单,否则无法提交审核

        // 更新审核时间到期时间
        if (order != null) {
          order.setVerifyDate(new Date());
          order.setExpireDate(DateUtils.addYears(new Date(), 1));
          if (!orderService.updateById(order)) {
            return R.error("更新订单失败");
          }
        }

        //查询客户端用户是否已经绑定在后台
        SysUserEntity informationVerifyUser = sysUserService.getBaseMapper()
          .selectOne(new QueryWrapper<SysUserEntity>()
            .eq("app_uid", hyInformationVerify.getUid()));

        SysUserRoleEntity userRoleEntity = new SysUserRoleEntity();
        userRoleEntity.setRoleId(FrogConstant.Role.MEDIA);

        //如果系统用户不存在，创建系统用户，创建用户角色管理
        if (ObjectUtil.isNull(informationVerifyUser)) {
          int duplicateName = sysUserService.getBaseMapper()
            .selectCount(new QueryWrapper<SysUserEntity>().eq("username",hyInformationVerify.getCompanyName()));
          if (duplicateName>0){
            return R.error("系统用户已存在该公司名");
          }

          informationVerifyUser = new SysUserEntity();
          informationVerifyUser.setUserId(hyInformationVerify.getUid().longValue());
          informationVerifyUser.setUsername(hyInformationVerify.getUsername());
          informationVerifyUser.setMobile(hyInformationVerify.getPhone());
          sysUserService.getBaseMapper().insert(informationVerifyUser);
          userRoleEntity.setUserId(informationVerifyUser.getUserId());
          sysUserRoleService.getBaseMapper().insert(userRoleEntity);
        } else {
          //如果系统用户存在,查询用户角色是否已经存在关联
          if (sysUserRoleService.getBaseMapper()
            .selectCount(new QueryWrapper<SysUserRoleEntity>()
              .eq("user_id", informationVerifyUser.getUserId())
              .eq("role_id",FrogConstant.Role.MEDIA)) < 1) {
            userRoleEntity.setUserId(informationVerifyUser.getUserId());
            sysUserRoleService.getBaseMapper().insert(userRoleEntity);
          };
        }
        hyInformationVerifyService.updateById(result);
        return R.ok("审核通过");
      }
      hyInformationVerifyService.updateById(result);
      return R.ok("审核未通过");
    }
    return R.error("请登录");
  }

  @RequestMapping(value = "recommend", method = RequestMethod.POST)
  @ApiOperation("推荐咨询号")
  public R recommendMedia(@RequestBody RecommendForm form) {
    HyInformationVerifyEntity verifyEntity = new HyInformationVerifyEntity();
    BeanUtils.copyProperties(form, verifyEntity);
    verifyEntity.setUpdateTime(new Date());

    if (hyInformationVerifyService.updateById(verifyEntity)) {
      if(form.getIsRecommend()==1) {
        return R.ok("推荐成功");
      }
      return R.ok("取消推荐成功");
    }
    return R.error();
  }

  @RequestMapping(value = "enable", method = RequestMethod.POST)
  @ApiOperation("启用咨询号")
  public R enableMedia(@RequestBody EnableMediaForm form) {
    HyInformationVerifyEntity verifyEntity = new HyInformationVerifyEntity();
    BeanUtils.copyProperties(form, verifyEntity);
    verifyEntity.setUpdateTime(new Date());
    if (hyInformationVerifyService.updateById(verifyEntity)) {
      if(form.getEnableState()==1){
        return R.ok("启用成功");
      }
      return R.ok("禁用用成功");
    }
    return R.error();
  }

  @RequestMapping(value = "getallRecord", method = RequestMethod.GET)
  @ApiOperation("资讯号审核列表")
  public R getAllVerifyRecord(@RequestParam Map<String, Object> map) {
    return R.ok().put("data", hyInformationVerifyService.getAllVerifyRecord(new QueryExt<>(map)));
  }

  @RequestMapping(value = "del/record", method = RequestMethod.DELETE)
  @ApiOperation("后台删除记录")
  public R delRecord(Integer uid) {
    Map<String, Object> columnMap = new HashMap<>(1);
    columnMap.put("uid", uid);

    if (hyInformationVerifyService.getBaseMapper().deleteByMap(columnMap) > 0) {
      return R.ok("删除成功");
    }
    return R.error("删除失败");
  }

  /**
   * 新建资讯号审核
   *
   * @param hyInformationVerify
   * @return
   */
  @RequestMapping(value = "verify/commit", method = RequestMethod.POST)
  @ApiOperation("新建资讯号审核")
  public R verifyInformation(@RequestBody VerifyMediaForm hyInformationVerify) {
    SysUserEntity sysUserEntity = getUser();
    if(ObjectUtil.isNotNull(sysUserEntity)) {
      User user = userService.getBaseMapper().selectOne(new QueryWrapper<User>()
        .eq("phone", hyInformationVerify.getOperatorPhone()));
      if(ObjectUtil.isNotNull(user)) {
        int recordresult = hyInformationVerifyService.getBaseMapper()
          .selectCount(new QueryWrapper<HyInformationVerifyEntity>()
            .eq("uid", user.getUid().intValue()));
        if (recordresult > 0) {
          return R.error("已存在该用户下的审核记录");
        }
        if (StringUtils.isBlank(hyInformationVerify.getUserName())) {
          return R.error("用户名不可以为空");
        }
        int result = hyInformationVerifyService.getBaseMapper()
          .selectCount(new QueryWrapper<HyInformationVerifyEntity>()
            .eq("user_name", hyInformationVerify.getUserName()));
        if (result > 0) {
          return R.error("用户名重复");
        }
        int duplicateName = sysUserService.getBaseMapper()
          .selectCount(new QueryWrapper<SysUserEntity>().eq("username",hyInformationVerify.getCompanyName()));
        if (duplicateName>0){
          return R.error("系统用户已存在该公司名");
        }

        if (hyInformationVerifyService.commitVerify(hyInformationVerify, user.getUid()) > 0) {
          return R.ok("提交审核成功");
        }
        return R.error("审核失败");
      }
      return R.error("请输入正确的手机号");
    }
    return R.error("请登录");
  }

  /**
   * 编辑图片上传
   *
   * @return
   */
  @RequestMapping(value = "uploadimg", method = RequestMethod.POST)
  @ApiOperation("资讯号图片上传")
  public R uploadImg(@RequestParam("file") MultipartFile file) {
    String result = null;
    if (file != null) {
      String fileName = UUID.randomUUID().toString() + file.getOriginalFilename()
        .substring(file.getOriginalFilename()
          .lastIndexOf("."), file.getOriginalFilename().length());
      result = UploadUtils.upload(UploadUtils.convertFile(file), fileName, FrogConstant.Path.INFORMATION_VERIFY_FU);
    }
    return R.ok(result);
  }

  @RequestMapping(value = "edit", method = RequestMethod.POST)
  @ApiOperation("运营编辑资讯号")
  public R edit(@RequestBody HyInformationVerifyEntity hyInformationVerify) {
    if (hyInformationVerify.getId() == null) {
      return R.error("请选择资讯号");
    }
    if (hyInformationVerifyService.updateById(hyInformationVerify)) {
      return R.ok("更新成功");
    }
    return R.error("更新失败");
  }

  /**
   * 编辑公司简介
   *
   * @return
   */
  @RequestMapping(value = "edit/companyProfile", method = RequestMethod.POST)
  @ApiOperation("编辑公司简介")
  public R editCompanyProfile(@RequestBody EditCompanyProfileForm form) {
    HyInformationVerifyEntity verifyEntity = new HyInformationVerifyEntity();
    BeanUtils.copyProperties(form, verifyEntity);
    verifyEntity.setUpdateTime(new Date());
    if (hyInformationVerifyService.updateById(verifyEntity)) {
      return R.ok("更新成功");
    }
    return R.error("更新失败");
  }
}
